package com.sunxd.limit.registrar;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/10/21 20:03
 */
public class AutoConfiguredLimitRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
    private DefaultListableBeanFactory beanFactory;


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        String basePackage = "com.sunxd.limit.core";
        boolean useDefaultFilters = false; //是否使用默认的filter，使用默认的filter意味着只扫描那些类上拥有Component注解的类。
        ClassPathScanningCandidateComponentProvider beanScanner = new ClassPathScanningCandidateComponentProvider(useDefaultFilters);
        beanScanner.addIncludeFilter(new AnnotationTypeFilter(Component.class)); // 拦截指定注解的类 可上面开启或者这里注册
        Set<BeanDefinition> beanDefinitions = beanScanner.findCandidateComponents(basePackage);
        for (BeanDefinition beanDefinition : beanDefinitions) {
            AnnotationBeanNameGenerator annotationBeanNameGenerator = new AnnotationBeanNameGenerator();
		    String beanName = annotationBeanNameGenerator.generateBeanName(beanDefinition, beanFactory);
            registry.registerBeanDefinition(beanName,beanDefinition);
        }
    }
}
